import 'package:flutter/material.dart';

/// @date 2020/08/05  10:44
/// @author 程志强
/// @des  异步UI更新  StreamBuilder

class StreamBuilderRoute extends StatefulWidget {
  @override
  _StreamBuilderRouteState createState() => _StreamBuilderRouteState();
}

class _StreamBuilderRouteState extends State<StreamBuilderRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("异步UI更新：StreamBuilder"),
      ),
      body: Center(
        child: StreamBuilder(
            stream: mockStreamData(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasError) {
                // 请求失败，显示错误
                return Text("Error：${snapshot.error}");
              }
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text("没有stream");
                case ConnectionState.waiting:
                  return Text("等待数据。。。。");
                case ConnectionState.active:
                  return Text("active：${snapshot.data}");
                case ConnectionState.done:
                  return Text("stream已关闭");
                default:
                  // 请求未结束，显示loading
                  return CircularProgressIndicator();
              }
            }),
      ),
    );
  }

  Stream<int> mockStreamData() {
    return Stream.periodic(Duration(seconds: 1), (i) => i);
  }
}
